package com.jeeplus.itemInterface.integralInterface;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.service.AccountService;
import com.jeeplus.modules.address.entity.Address;
import com.jeeplus.modules.address.service.AddressService;
import com.jeeplus.modules.dynamicrecord.entity.DynamicRecord;
import com.jeeplus.modules.dynamicrecord.service.DynamicRecordService;
import com.jeeplus.modules.grouporders.entity.GroupOrders;
import com.jeeplus.modules.grouporders.service.GroupOrdersService;
import com.jeeplus.modules.grouprecord.entity.GroupRecord;
import com.jeeplus.modules.grouprecord.service.GroupRecordService;
import com.jeeplus.modules.groupreturn.entity.GroupReturn;
//import com.jeeplus.modules.integralorders.entity.IntegralDetail;
import com.jeeplus.modules.integraldetail.entity.IntegralDetail;
import com.jeeplus.modules.integraldetail.service.IntegralDetailService;
import com.jeeplus.modules.integralorders.entity.IntegralOrders;
import com.jeeplus.modules.integralorders.service.IntegralOrdersService;
import com.jeeplus.modules.integralrecord.entity.IntegralRecord;
import com.jeeplus.modules.integralrecord.service.IntegralRecordService;
import com.jeeplus.modules.integralvideo.entity.IntegralVideo;
import com.jeeplus.modules.integralvideo.service.IntegralVideoService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.ordersstore.entity.OrdersStore;
import com.jeeplus.modules.ordersstore.service.OrdersStoreService;
import com.jeeplus.modules.partitioninfo.entity.PartitionInfo;
import com.jeeplus.modules.partitioninfo.service.PartitionInfoService;
import com.jeeplus.modules.pointslottery.entity.PointsLottery;
import com.jeeplus.modules.pointslottery.service.PointsLotteryService;
import com.jeeplus.modules.sessions.entity.Sessions;
import com.jeeplus.modules.sessions.service.SessionsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Api(value = "integralInterfaceController",description = "积分抽奖接口")
@Controller
@RequestMapping(value = "${frontPath}/integral")
public class integralInterfaceController {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PointsLotteryService pointsLotteryService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private IntegralOrdersService integralOrdersService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private DynamicRecordService dynamicRecordService;
    @Autowired
    private OrdersStoreService ordersStoreService;
    @Autowired
    private SessionsService sessionsService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private IntegralVideoService integralVideoService;
    @Autowired
    private IntegralDetailService integralDetailService;


    @ApiOperation(value = "获取积分抽奖商品",notes = "获取积分抽奖商品")
    @GetMapping("/getIntegral")
    @ResponseBody
    public AjaxJson getGroups(){
        AjaxJson aj = new AjaxJson();
        //查询积分抽奖商品列表
        PointsLottery pointsLottery = new PointsLottery();
        pointsLottery.setIsEnd("0");
        List<PointsLottery> pointsLotteries = pointsLotteryService.findList(pointsLottery);
        aj.put("goodsList",pointsLotteries);
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "去兑换",notes = "去兑换")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",value = "商品id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("toExchange")
    @ResponseBody
    public AjaxJson toExchange(String goodsId){
        AjaxJson aj = new AjaxJson();
        //查询积分抽奖商品详情
        PointsLottery pointsLottery = pointsLotteryService.get(goodsId);
        if (pointsLottery == null){
            aj.setMsg("商品信息有误");
            aj.setSuccess(false);
            return aj;
        }
        aj.put("detail",pointsLottery);
        aj.setSuccess(true);
        return aj;
    }


    @ApiOperation(value = "购买",notes = "购买")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",value = "商品id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "num",value = "购买份数",required = true,dataType = "String",paramType = "query")
    })
    @PostMapping("purchase")
    @ResponseBody
    public AjaxJson purchase(String goodsId,String memberId,int num){
        AjaxJson aj = new AjaxJson();
        //查询用户信息
        Member member = memberService.get(memberId);
        if (member != null){
            PointsLottery pointsLottery = pointsLotteryService.get(goodsId);
            if (pointsLottery == null){
                aj.setSuccess(false);
                aj.setMsg("商品信息有误");
                return aj;
            }
            if (num > pointsLottery.getIntegralMember()){
                aj.setSuccess(false);
                aj.setMsg("当前份数不足");
                return aj;
            }
            //加锁，限制用户排队参加拼团
            Jedis jedis = new Jedis("localhost",6379);
            Long result = jedis.setnx("my_integral",memberId);
            if (result == 1){
                //设置有效期10秒
                jedis.expire("my_integral",10);
                aj = integralOrdersService.purchaseOrder(pointsLottery,member,num);
                jedis.del("my_integral");
            }else {
                aj.setSuccess(false);
                aj.setMsg("当前兑换人数过多，请重试！");
                return aj;
            }

        }else {
            aj.setMsg("用户信息有误");
            aj.setSuccess(false);
        }
        return aj;
    }


    @ApiOperation(value = "积分订单列表",notes = "积分订单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "flag",value = "订单标识（0全部1未中奖2已中奖）",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("getIntegralList")
    @ResponseBody
    public AjaxJson getIntegralList(String flag ,String memberId){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            List<IntegralOrders> ordersList = new ArrayList<>();
            switch (flag){
                case "1":
                    IntegralOrders integralOrders = new IntegralOrders();
                    integralOrders.setIsEnd("1");
                    integralOrders.setPrizeFlag("0");
                    integralOrders.setMember(member);
                    List<IntegralOrders> list = integralOrdersService.findList(integralOrders);
                    if (list.size()>0){
                        for (IntegralOrders orders : list) {
                            PointsLottery pointsLottery = pointsLotteryService.get(orders.getPointLottery().getId());
                            String[] pics = pointsLottery.getIntegralPic().split("\\|");
                            pointsLottery.setIntegralPic(pics[0]);
                            orders.setPointLottery(pointsLottery);
                        }
                    }
                    ordersList.addAll(list);
                    aj.put("orderList",ordersList);
                    aj.setSuccess(true);
                    return aj;
                case "2":
                    IntegralOrders integralOrders1 = new IntegralOrders();
                    integralOrders1.setIsEnd("1");
                    integralOrders1.setPrizeFlag("1");
                    integralOrders1.setMember(member);
                    List<IntegralOrders> list1 = integralOrdersService.findList(integralOrders1);
                    if (list1.size()>0){
                        for (IntegralOrders orders : list1) {
                            PointsLottery pointsLottery = pointsLotteryService.get(orders.getPointLottery().getId());
                            String[] pics = pointsLottery.getIntegralPic().split("\\|");
                            pointsLottery.setIntegralPic(pics[0]);
                            orders.setPointLottery(pointsLottery);
                        }
                    }
                    ordersList.addAll(list1);
                    aj.put("orderList",ordersList);
                    aj.setSuccess(true);
                    return aj;
                 default:
                     IntegralOrders integralOrders2 = new IntegralOrders();
                     integralOrders2.setMember(member);
                     List<IntegralOrders> list2 = integralOrdersService.findList(integralOrders2);
                     if (list2.size()>0){
                         for (IntegralOrders orders : list2) {
                             PointsLottery pointsLottery = pointsLotteryService.get(orders.getPointLottery().getId());
                             String[] pics = pointsLottery.getIntegralPic().split("\\|");
                             pointsLottery.setIntegralPic(pics[0]);
                             orders.setPointLottery(pointsLottery);
                             if ("0".equals(orders.getIsEnd())){
                                 orders.setPrizeFlag("2");
                             }
                         }
                     }
                     ordersList.addAll(list2);
                     aj.put("orderList",ordersList);
                     aj.setSuccess(true);
                     return aj;
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
            return aj;
        }
    }


    @ApiOperation(value = "积分订单详情",notes = "积分订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo",value = "订单编号",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("getIntegralDetail")
    @ResponseBody
    public AjaxJson getIntegralDetail(String orderNo ,String memberId){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            IntegralOrders integralOrders = new IntegralOrders();
            integralOrders.setMember(member);
            integralOrders.setOrderNo(orderNo);
            List<IntegralOrders> list = integralOrdersService.findList(integralOrders);
            if (list.size()>0){
                for (IntegralOrders orders : list) {
                    PointsLottery pointsLottery = pointsLotteryService.get(orders.getPointLottery().getId());
                    String[] pics = pointsLottery.getIntegralPic().split("\\|");
                    pointsLottery.setIntegralPic(pics[0]);
                    orders.setPointLottery(pointsLottery);
                    if ("0".equals(orders.getIsEnd())){
                        orders.setPrizeFlag("2");
                    }
                }
                aj.put("orderDetail",list.get(0));
            }else {
                aj.setSuccess(false);
                aj.setMsg("订单信息有误");
                return aj;
            }
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
            return aj;
        }
        return aj;
    }

    @ApiOperation(value = "获取视频",notes = "获取视频")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("getVideo")
    @ResponseBody
    public AjaxJson getVideo(String memberId){
        AjaxJson aj = new AjaxJson();
        Member member = memberService.get(memberId);
        if (member != null){
            List<IntegralVideo> list = integralVideoService.findList(new IntegralVideo());
            if (list.size()>0){
                int result = (int) (Math.random()*list.size());
                aj.put("myVideo",list.get(result).getVideoDetail());
            }else {
                aj.put("myVideo","");
            }
            aj.setSuccess(true);
        }else {
            aj.setSuccess(false);
            aj.setMsg("用户信息有误");
            return aj;
        }
        return aj;
    }

    @ApiOperation(value = "看完视频加积分",notes = "看完视频加积分")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @PostMapping("completeVideo")
    @ResponseBody
    public AjaxJson completeVideo(String memberId){
        AjaxJson aj = new AjaxJson();
        try {
            Member member = memberService.get(memberId);
            if (member != null){
                IntegralDetail integralDetail = new IntegralDetail();
                integralDetail.setIntegralType("4");
                integralDetail.setMember(member);
                int count = integralDetailService.findVideoByDay(integralDetail);
                if (count >= 5){
                    aj.setSuccess(false);
                    aj.setMsg("每日最多获取5次积分");
                    return aj;
                }
                integralDetailService.saveByVideo(member);
                aj.setSuccess(true);
                aj.setMsg("成功获得积分");
            }else {
                aj.setSuccess(false);
                aj.setMsg("用户信息有误");
                return aj;
            }
        }catch (Exception e){
            e.printStackTrace();
            aj.setSuccess(false);
            aj.setMsg(e.getMessage());
            return aj;
        }
        return aj;
    }


    @ApiOperation(value = "视频积分明细",notes = "视频积分明细")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("getPrizeList")
    @ResponseBody
    public AjaxJson getPrizeList(String memberId){
        AjaxJson aj = new AjaxJson();
        try {
            Member member = memberService.get(memberId);
            if (member != null){
                IntegralDetail integralDetail = new IntegralDetail();
                integralDetail.setMember(member);
                integralDetail.setIntegralType("4");
                List<IntegralDetail> list = integralDetailService.findListLimit(integralDetail);
                aj.setSuccess(true);
                aj.put("list",list);
            }else {
                aj.setSuccess(false);
                aj.setMsg("用户信息有误");
                return aj;
            }
        }catch (Exception e){
            e.printStackTrace();
            aj.setSuccess(false);
            aj.setMsg(e.getMessage());
            return aj;
        }
        return aj;
    }

    @ApiOperation(value = "今日视频次数",notes = "今日视频次数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
    })
    @GetMapping("getWatchedTimes")
    @ResponseBody
    public AjaxJson getWatchedTimes(String memberId){
        AjaxJson aj = new AjaxJson();
        try {
            Member member = memberService.get(memberId);
            if (member != null){
                IntegralDetail integralDetail = new IntegralDetail();
                integralDetail.setIntegralType("4");
                integralDetail.setMember(member);
                int count = integralDetailService.findVideoByDay(integralDetail);
                aj.setSuccess(true);
                aj.put("count",count);
            }else {
                aj.setSuccess(false);
                aj.setMsg("用户信息有误");
                return aj;
            }
        }catch (Exception e){
            e.printStackTrace();
            aj.setSuccess(false);
            aj.setMsg(e.getMessage());
            return aj;
        }
        return aj;
    }


//    @ApiOperation(value = "用户积分详情",notes = "用户积分详情")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "memberId",value = "用户id",required = true,dataType = "String",paramType = "query")
//    })
//    @GetMapping("getMembersIntegral")
//    @ResponseBody
//    public AjaxJson getMembersIntegral(String memberId){
//        AjaxJson aj = new AjaxJson();
//        Member member = memberService.get(memberId);
//        if (member != null){
//            Account account = accountService.get(member.getAccount().getId());
//
//            List<IntegralDetail> integralDetails = new ArrayList<>();
//            IntegralOrders integralOrders = new IntegralOrders();
//            integralOrders.setMember(member);
//            List<IntegralOrders> list = integralOrdersService.findList(integralOrders);
//            if (list.size()>0){
//                for (IntegralOrders orders : list) {
//                    IntegralDetail integralDetail = new IntegralDetail();
//                    integralDetail.setCostTime(DateUtils.formatDateTime(orders.getCreateDate()));
//                    integralDetail.setIntegral("-"+orders.getMoney().toString());
//                    integralDetail.setOrderNo(orders.getOrderNo());
//                    integralDetail.setType("积分兑换");
//                    integralDetails.add(integralDetail);
//                }
//            }
//
//            OrdersStore ordersStore = new OrdersStore();
//            ordersStore.setMember(member);
//            List<OrdersStore> list1 = ordersStoreService.findList(ordersStore);
//            if (list1.size()>0){
//                for (OrdersStore store : list1) {
//                    if (!"1".equals(store.getOrdersStatus()) && !"5".equals(store.getOrdersStatus()) && store.getJifen() != null && store.getJifen() != 0){
//                        IntegralDetail integralDetail = new IntegralDetail();
//                        integralDetail.setType("积分购买");
//                        integralDetail.setOrderNo(store.getOrdersNo());
//                        integralDetail.setIntegral("-"+store.getJifen().toString());
//                        integralDetail.setCostTime(DateUtils.formatDateTime(store.getPaytime()));
//                        integralDetails.add(integralDetail);
//                    }
//                }
//            }
//
//            DynamicRecord dynamicRecord = new DynamicRecord();
//            dynamicRecord.setMember(member);
//            List<DynamicRecord> list2 = dynamicRecordService.findList(dynamicRecord);
//            if (list2.size()>0){
//                for (DynamicRecord record : list2) {
//                    if ("幸运收益".equals(record.getName())){
//                        IntegralDetail integralDetail = new IntegralDetail();
//                        integralDetail.setCostTime(DateUtils.formatDateTime(record.getCreateDate()));
//                        integralDetail.setIntegral("+"+record.getMoney().toString());
//                        if (StringUtils.isNotBlank(record.getRemarks())){
//                            Sessions sessions = sessionsService.get(record.getRemarks());
//                            integralDetail.setOrderNo(sessions!=null?sessions.getSessionsName():"");
//                        }
//                        integralDetail.setType("幸运收益");
//                        integralDetails.add(integralDetail);
//                    }
//                }
//            }
//            integralDetails = integralDetails.stream().sorted(Comparator.comparing(IntegralDetail::getCostTime).reversed()).collect(Collectors.toList());
//            aj.put("integralDetails",integralDetails);
//            aj.put("integral",account!=null?account.getIntegral():0);
//            aj.setSuccess(true);
//        }else {
//            aj.setSuccess(false);
//            aj.setMsg("用户信息有误");
//            return aj;
//        }
//        return aj;
//    }

}
